import type { Context, Next } from "koa";
import { HttpException } from "@/error/exception";
import { container } from "@/services/register";

export default async (ctx: Context, next: Next) => {
  const token = ctx.headers["authorization"];
  if (!token) {
    throw new HttpException("缺少 Authorization", 401);
  }

  // Bearer <token> 格式，去掉 "Bearer " 前缀
  const tokenValue = token.split(" ")[1];

  // 将解码后的用户信息附加到请求对象上
  ctx.state.user = container.resolve("JsonwebtokenService").verify(tokenValue);

  await next();
};
